package com.yinhe.music.yhmusic.video;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.common.emoji.ExpressionGridFragment;
import com.yinhe.music.common.emoji.ExpressionShowFragment;
import com.yinhe.music.common.emoji.widget.ExpressionEditText;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.CommentListAdapter;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BasePresneterActivity;
import com.yinhe.music.yhmusic.base.IBaseModel;
import com.yinhe.music.yhmusic.base.IBaseView;
import com.yinhe.music.yhmusic.comment.CommentListPresenter;
import com.yinhe.music.yhmusic.comment.CommentSection;
import com.yinhe.music.yhmusic.comment.ICommentListContract;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.model.MvsInfo;
import com.yinhe.music.yhmusic.share.SharePresenter;
import com.yinhe.music.yhmusic.utils.KeyboardUtil;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.utils.ViewUtils;
import com.yinhe.music.yhmusic.widget.CustomLoadMoreView;
import com.yinhe.music.yhmusic.widget.VideoPlayer;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class VideoPlayingActivity extends BasePresneterActivity implements BaseQuickAdapter.OnItemChildClickListener,
        ExpressionGridFragment.ExpressionClickListener, ExpressionGridFragment.ExpressionDeleteClickListener,
        ICommentListContract.ICommentListView, IVideoPlayingContract.IVideoPlayingView, View.OnClickListener {
    public static final String VIDEO_URL = "VIDEO_URL";

    @BindView(R.id.root_rl)
    RelativeLayout rootRl;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.empty_text)
    TextView emptyText;
    @BindView(R.id.edit_comment)
    ExpressionEditText editComment;
    @BindView(R.id.send)
    ImageView send;
    @BindView(R.id.emoji)
    ImageView emoji;
    @BindView(R.id.fl_emogi)
    FrameLayout fl_emogi;

    private ExpressionShowFragment expressionShowFragment;
    private boolean isEmogiShow;
    private boolean keyboardShown;
    private int supportSoftInputHeight;
    private static final int MAX_COMMENT_COUNT = 255;

    private VideoPlayer videoPlayer;
    private TextView name, author, playNum, date, tvCollection, tvShare, tvLike;
    MvsInfo mvsInfo;
    private String videoUrl;
    private Drawable collectT, collectF;

    CommentListPresenter commentPresenter;
    VideoPlayingPresenter videoPlayingPresenter;

    private CommentListAdapter commentAdapter;
    private int mPageNum;
    private int position;
    private int commentLikeState;
    private CommentSection commentSection;

    @Override
    public BasePresenter getPresenter() {
        return videoPlayingPresenter;
    }

    @Override
    public void initPresenter() {
        commentPresenter = new CommentListPresenter();
        commentPresenter.attachModelView(new BaseModel(), this);

        videoPlayingPresenter = new VideoPlayingPresenter();
        videoPlayingPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        hideSystemNavigationBar();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);

        if (getIntent() != null) {
            mvsInfo     = (MvsInfo) getIntent().getSerializableExtra("mv");
            videoUrl    = getIntent().getStringExtra(VIDEO_URL);
        }
        ButterKnife.bind(this);
        UmengEventUtils.playVideo(this);
        setComment();
        initView();
        initData(true);
    }

    /*
     * 隐藏系统导航栏
     * */
    private void hideSystemNavigationBar() {
        if (Build.VERSION.SDK_INT < 19) {
            View view = this.getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /*
     * 初始化发送图标
     * */
    private void setComment() {
        editComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String content = editComment.getText().toString();
                if (content.length() > 0) {
                    send.setImageResource(R.drawable.ic_send_clickable);
                    send.setClickable(true);
                } else {
                    send.setImageResource(R.drawable.ic_send_unclikable);
                    send.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editComment.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                fl_emogi.setVisibility(View.GONE);
            }
        });

        editComment.setOnClickListener((v) -> {
            if (isEmogiShow) {
                isEmogiShow = false;
                fl_emogi.setVisibility(View.GONE);
            }
        });
    }

    private void initView() {
        RxBus.get().register(this);

        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        commentAdapter = new CommentListAdapter(null);
        commentAdapter.addHeaderView(getHeadView(LayoutInflater.from(this)));
        commentAdapter.setLoadMoreView(new CustomLoadMoreView());
        commentAdapter.setOnLoadMoreListener(() -> {
            if (mPage <= mPageNum) {
                initData(false);
            } else {
                commentAdapter.loadMoreEnd();
            }
        }, recyclerView);
        commentAdapter.setPreLoadNumber(5);
        commentAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        commentAdapter.setOnItemChildClickListener(this);
        recyclerView.setAdapter(commentAdapter);

        setListenerToRootView();
        setRootOnTouchListener();
    }

    /*
     * 添加头布局
     * */
    private View getHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.header_video_play, (ViewGroup) recyclerView.getParent(), false);

        videoPlayer  = view.findViewById(R.id.video_player);
        name         = view.findViewById(R.id.name);
        author       = view.findViewById(R.id.author);
        playNum      = view.findViewById(R.id.play_num);
        date         = view.findViewById(R.id.date);
        tvCollection = view.findViewById(R.id.tv_collection);
        tvShare      = view.findViewById(R.id.tv_share);
        tvLike       = view.findViewById(R.id.tv_like);
        name.setText(mvsInfo.getMovieName());
        author.setText(mvsInfo.getSingerName());
        playNum.setText(mvsInfo.getPlayNum() + "次播放");
        date.setText(mvsInfo.getCreateTime());
        tvLike.setText(mvsInfo.getLikeNum() + "");
        videoPlayer.setUp(videoUrl, true, mvsInfo.getMovieName());
        //增加封面
        ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        GlideHelper.setImageResource(imageView, mvsInfo.getImage());
        videoPlayer.setThumbImageView(imageView);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置全屏按键功能
        videoPlayer.getFullscreenButton().setOnClickListener((v) ->
                videoPlayer.startWindowFullscreen(videoPlayer.getContext(), false, true));
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener((v) -> onBackPressed());
        videoPlayer.startPlayLogic();

        collectT = getResources().getDrawable(R.drawable.ic_heart_red);
        collectT.setBounds(0, 0, 64, 64);
        collectF = getResources().getDrawable(R.drawable.ic_heart_grey);
        collectF.setBounds(0, 0, 64, 64);
        tvCollection.setCompoundDrawables(null,mvsInfo.getCollectStatus() == 0
                ? collectF : collectT,null, null);
        tvCollection.setOnClickListener(this);
        tvShare.setOnClickListener(this);
        tvLike.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_share:
                videoPlayingPresenter.getShareInfo(IConstants.MOVIE, mvsInfo.getMovieId(), VideoPlayingActivity.this);
                break;
            case R.id.tv_collection:
                // 视频收藏
                videoPlayingPresenter.collect(mvsInfo.getMovieId(), mvsInfo.getCollectStatus());
                break;
            case R.id.tv_like:
                // 视频点赞
                videoPlayingPresenter.like(mvsInfo.getMovieId(), mvsInfo.getLikeStatus());
                break;
        }
    }

    // 视频点赞后UI
    @Override
    public void afterLikeUI(Boolean isLike) {
        mvsInfo.setLikeStatus(isLike ? 1 : 0);
    }

    // 视频收藏后UI
    @Override
    public void afterCollectUI(Boolean isCollect) {
        tvCollection.setCompoundDrawables(null,isCollect ? collectT : collectF,null, null);
        mvsInfo.setCollectStatus(isCollect ? 1 : 0);
        mvsInfo.setItemType(MvsInfo.MORE);                     // 设置布局样式（蛋疼，分开写会死吗？）
        RxBus.get().post(RxBusEventType.Mv.COLLECT_MV, mvsInfo);
    }


    private void initData(boolean isRefresh) {
        if (isRefresh) {
            mPage = 1;
            mPageSize = 15;
        }
        commentPresenter.getCommentList(mPage, mPageSize, IConstants.MOVIE, mvsInfo.getMovieId());
    }

    /*
     * 评论点赞
     * */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (Preferences.getLoginSn().isEmpty()) {
            Toast.makeText(this, "重新登陆", Toast.LENGTH_SHORT).show();
            startLogin();
            return;
        }
        this.position = position;
        commentSection = (CommentSection) adapter.getData().get(position);
        commentLikeState = commentSection.t.getCollectStatus();
        commentPresenter.collect(commentSection.t.getCommentid(), IConstants.COMMENT, commentLikeState);
    }


    /*
     * 表情
     * */
    @OnClick(R.id.emoji)
    public void showEmoji() {
        if (isEmogiShow) {
            isEmogiShow = false;
            fl_emogi.setVisibility(View.GONE);
            KeyboardUtil.showKeyboard(this, editComment);
            emoji.setImageResource(R.drawable.ic_emoji);
        } else {
            int delay = 0;
            if (keyboardShown) {
                KeyboardUtil.hideKeyboard(this);
                emoji.setImageResource(R.drawable.emoji_keyboard);
                delay = 300;
            }
            mHandler.postDelayed(this::replaceEmogi, delay);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setRootOnTouchListener() {
        rootRl.setOnTouchListener((v, event) -> {
            KeyboardUtil.hideKeyboard(this);
            emoji.setImageResource(R.drawable.emoji_keyboard);
            return false;
        });
    }

    /**
     * 动态监听键盘状态
     */
    private void setListenerToRootView() {
        rootRl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                keyboardShown = KeyboardUtil.isKeyboardShown(rootRl);
                if (fl_emogi != null) {
                    if (keyboardShown) {
                        emoji.setImageResource(R.drawable.ic_emoji);
                        if (isEmogiShow) {
                            isEmogiShow = false;
                            fl_emogi.setVisibility(View.GONE);
                        }
                        if (supportSoftInputHeight != ViewUtils.getSupportSoftInputHeight(VideoPlayingActivity.this)) {
                            rootRl.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            supportSoftInputHeight = ViewUtils.getSupportSoftInputHeight(VideoPlayingActivity.this);
                            fl_emogi.getLayoutParams().height = supportSoftInputHeight;
                            fl_emogi.requestLayout();
                            rootRl.getViewTreeObserver().addOnGlobalLayoutListener(this);
                        }
                    } else {
                        emoji.setImageResource(R.drawable.emoji_keyboard);
                        if (!isEmogiShow) {
                            fl_emogi.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }

    /**
     * 表情显示
     */
    private void replaceEmogi() {
        isEmogiShow = true;
        fl_emogi.setVisibility(View.VISIBLE);

        if (expressionShowFragment == null) {
            expressionShowFragment = ExpressionShowFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_emogi,
                    ExpressionShowFragment.newInstance()).commit();
        }
    }

    /**
     * 这里必须实现表情点击后才能把具体表情传入edittext
     *
     * @param str
     */
    @Override
    public void expressionClick(String str) {
        ExpressionShowFragment.input(editComment, str);
    }

    @Override
    public void expressionDeleteClick(View v) {
        ExpressionShowFragment.delete(editComment);
    }

    /**
     * 发送评论
     */
    @OnClick(R.id.send)
    public void sendComment() {
        hideSoftKeyboard();
        if (!Preferences.getLoginSn().isEmpty()) {
            String content = editComment.getText().toString();
            if (!TextUtils.isEmpty(content) && content.length() < MAX_COMMENT_COUNT) {
                commentPresenter.comment(mvsInfo.getMovieId(), content, IConstants.MOVIE);
            } else {
                Toast.makeText(this, "请输入少于255个字", Toast.LENGTH_SHORT).show();
            }
        } else {
            startHome();
        }
    }

    /*
     * 渲染评论列表
     * */
    @Override
    public void setCommentListUI(List<CommentSection> commentSectionList, int pageNum) {
        mPageNum = pageNum;
        setLoadMoreList(commentSectionList, mPageNum, commentAdapter);
    }

    /*
     * 空布局显示
     * */
    @Override
    public void showEmptyUI(int visibility) {
        emptyText.setVisibility(visibility);
    }

    /*
     * 评论成功
     * */
    @Override
    public void setCommentUI() {
        UmengEventUtils.comment(this);
        KeyboardUtil.hideKeyboard(this);
        emoji.setImageResource(R.drawable.emoji_keyboard);
        if (isEmogiShow) {
            isEmogiShow = false;
            fl_emogi.setVisibility(View.GONE);
        }

        editComment.setText("");
        editComment.setHint("写下你的评论");
        initData(true);
    }

    /*
     * 渲染更多数据失败
     * */
    @Override
    public void setLoadMoreFailUI() {
        commentAdapter.loadMoreFail();
    }

    /*
     * 更新收藏/点赞状态
     * */
    @Override
    public void updateCollectUI() {
        if (commentLikeState == 0) {
            int num = commentSection.t.getLikeNum() + 1;
            commentSection.t.setLikeNum(num);
            commentSection.t.setCollectStatus(1);
            commentAdapter.setData(position, commentSection);
        } else {
            int num = commentSection.t.getLikeNum() - 1;
            commentSection.t.setLikeNum(num > 0 ? num : 0);
            commentSection.t.setCollectStatus(0);
            commentAdapter.setData(position, commentSection);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (isEmogiShow || KeyboardUtil.isKeyboardShown(rootRl)) {
            isEmogiShow = false;
            fl_emogi.setVisibility(View.GONE);
            KeyboardUtil.hideKeyboard(this);
            emoji.setImageResource(R.drawable.emoji_keyboard);
            videoPlayer.setVideoAllCallBack(null);
        } else {
            finish();
        }
    }
}
